package com.example.youzhengyang

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.youzhengyang.databinding.ItemWordBinding

class WordAdapter(private val onLongClick: (Word) -> Unit) :
    ListAdapter<Word, WordAdapter.WordViewHolder>(WordDiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WordViewHolder {
        return WordViewHolder(
            ItemWordBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
        )
    }

    override fun onBindViewHolder(holder: WordViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    inner class WordViewHolder(private val binding: ItemWordBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(word: Word) {
            binding.textViewWord.text = word.word
            binding.textViewWord.setTextColor(binding.root.context.getColor(R.color.red))
            binding.root.setOnLongClickListener {
                onLongClick(word)
                true
            }
        }
    }
}

class WordDiffCallback : DiffUtil.ItemCallback<Word>() {
    override fun areItemsTheSame(oldItem: Word, newItem: Word) = oldItem.id == newItem.id
    override fun areContentsTheSame(oldItem: Word, newItem: Word) = oldItem == newItem
} 